// IMPORT


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*IMPORT][IMPORT:1]]
import * as Equal from "./equal.module.js"
import * as Json from "./json.module.js"
import * as Sample from "./sample.module.js"
// IMPORT:1 ends here
// insert


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*insert][insert:1]]
let optionsLocalStorageKey="Database.options"
let options=restoreFromLocalStorage(optionsLocalStorageKey)||[]

function saveToRam(object){
    if(!optionsExistP(object)){
        options.push(object)
    }else{
        options[getOptionsIndex(object.标题)].方案=object.方案
    }
    saveToLocalStorage(optionsLocalStorageKey,options)
    return options
}

function localStorageSet(key,value){
    return saveToLocalStorage(key,value)
}

function saveToLocalStorage(key,value){
    if(value){
        localStorage.setItem(key,Json.string(value))
    }
    return value
}
// insert:1 ends here
// select


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*select][select:1]]
function optionsExistP(object){
    return getOptionsIndex(object.标题)!==-1
}

function getOptionsIndex(title){
    let titles=[]
    options.forEach(function(object){
        titles.push(object.标题)
    })
    return titles.indexOf(title)
}

function localStorageGet(key){
    return restoreFromLocalStorage(key)
}

function restoreFromLocalStorage(key){
    try{
        return Json.parse(localStorage.getItem(key))
    }catch(err){
        console.log(err)
        return
    }
}
// select:1 ends here
// delete


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*delete][delete:1]]
function clearLocalStorage(){
    localStorage.clear()
}

function clearRam(){
    options=[]
}

function deleteOptions(index){
    if(index>0){
        options.splice(index,1)
        saveToLocalStorage(optionsLocalStorageKey,options)
    }
}

function deleteOptionsByTitle(title){
    deleteOptions(getOptionsIndex(title))
}
// delete:1 ends here
// Init


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*Init][Init:1]]
function init(){
    clearLocalStorage()
    clearRam()
}
// Init:1 ends here
// setDefaultOptions


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*setDefaultOptions][setDefaultOptions:1]]
let defaultOptionsKey="Sample.options"

function setDefaultOptions(options){
    Sample.setf(options)
    localStorageSet(defaultOptionsKey,options)
}

function restoreDefaultOptions(){
    Sample.setf(localStorageGet(defaultOptionsKey))
}
// setDefaultOptions:1 ends here
// EXPORT


// [[file:~/literate-programming/soul-hunter-awakening-damage-calculator-web-edition.org::*EXPORT][EXPORT:1]]
export{saveToRam,init,localStorageSet,localStorageGet,restoreDefaultOptions,setDefaultOptions,deleteOptionsByTitle}
// EXPORT:1 ends here
